package com.formula.datastructure.exam.other;

import com.formula.datastructure.util.DataUtil;

public class Heap {
    private Integer[] array;
    int lastIdx = -1;

    public void init(Integer[] input) {
        int N = input.length;

        array = new Integer[2 * N];

        for (int i = 0; i < N; i++) {
            array[++lastIdx] = input[i];
            siftUp(lastIdx);
        }
    }

    public void add(Integer data) {
        array[++lastIdx] = data;
        siftUp(lastIdx);
    }

    private void siftUp(int idx) {
        Integer temp;
        for (int i = getParent(idx); i >= 0; i = getParent(idx)) {
            if (array[i] < array[idx]) {
                temp = array[i];
                array[i] = array[idx];
                array[idx] = temp;
                idx = i;
            } else {
                break;
            }
        }
    }


    private int getParent(int idx) {
        if (idx == 0) {
            return -1;
        } else {
            return (idx - 1) / 2;
        }
    }

    public static void main(String[] args) {

        Heap heap = new Heap();

        int size = 15;
        int range = 500;
        Integer[] array = DataUtil.genUniqueArray(size, range);
        DataUtil.printIndex(size);
        DataUtil.printArray(array);
        heap.init(array);
        array = DataUtil.genUniqueArray(size, range);
        DataUtil.printIndex(size);
        DataUtil.printArray(array);
        for (Integer data : array) {
            heap.add(data);
        }

        DataUtil.printArray(heap.array);
    }
}
